package localizer.main;
import java.util.Calendar;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.SmsMessage;
import android.text.format.Time;
import android.util.Log;

public class SmsReceiver extends BroadcastReceiver {
	
	public final static String ID_LOC = "aZ*m1871623ASSa,,<>#guthyerrzehgay";
	
    @Override
    public void onReceive(Context context, Intent intent) {
    	Log.d("mensagem", "recebida");
    	Config config = Config.getInstance(context.getApplicationContext());
    	if( config.hasUser(context.getApplicationContext())){
			final String username = config.getUsername(context.getApplicationContext());
			final String password = config.getPassword(context.getApplicationContext());
	        Bundle bundle = intent.getExtras();
	        boolean flag=false;
	        boolean flag2=false;
	        boolean flag3=false;
	        if (bundle != null) {
	        	
	            Object[] pdus = (Object[]) bundle.get("pdus");
	            SmsMessage[] msgs = new SmsMessage[pdus.length];
	            for (int i = 0; i < msgs.length; i++) {
	                msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]);                
	                final String message = msgs[i].getMessageBody().toString();
	                if(message.contains(username) && message.contains(password)){
	                	//flag=true;
	                } else if( message.contains(ID_LOC)){
	                	String[] aux = message.split(" ");
			        	Time time = new Time();
			        	time.setToNow();
			        	Config.getInstance(context.getApplicationContext()).createLoc(context.getApplicationContext(), aux[0], aux[1], msgs[i].getOriginatingAddress().toString(),java.text.DateFormat.getDateTimeInstance().format(Calendar.getInstance().getTime()) );
			        	
			        	String ns = Context.NOTIFICATION_SERVICE;
			        	NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
			        	int icon = R.drawable.logophone;
			        	CharSequence tickerText = "Hello";
			        	long when = System.currentTimeMillis(); 
			        	CharSequence contentTitle = "Phone Finder"; 
			        	CharSequence contentText = "Location Received";
			        	Intent dialogIntent = new Intent ( context.getApplicationContext(), MapAppActivity.class);
						dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			        	dialogIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			        	dialogIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
			        	PendingIntent contentIntent = PendingIntent.getActivity(context.getApplicationContext(), 0, dialogIntent, 0);
			        	Notification notification = new Notification(icon, tickerText, when);
			        	notification.setLatestEventInfo(context.getApplicationContext(), contentTitle, contentText, contentIntent);
			        	notification.flags |= Notification.FLAG_AUTO_CANCEL;
			        	notification.defaults |= Notification.DEFAULT_VIBRATE;
			        	notification.defaults |= Notification.DEFAULT_SOUND;
			        	final int HELLO_ID = 1;

			        	mNotificationManager.notify(HELLO_ID, notification);

			        	
			        	
						flag = true;
	                }
	                if(message.contains(username) && message.contains(password)&& message.contains("ring") && config.isEnableCheckRingByMsg(context.getApplicationContext())){
	                	flag2 = true;
	                	if(message.contains("silent")){
	                		flag3 = true;
	                	}
	                	flag = true;
	                }
	                if( message.contains(username) && message.contains(password) &&  message.contains("loc") && config.isEnableCheckLocByMsg(context.getApplicationContext())){
	                	Log.d("pedido de loc de", msgs[i].getOriginatingAddress().toString());
		            	Intent intent2 = new Intent(context, StartServiceLocalization.class);
		            	String to = "sms";
		            	if( message.contains(ID_LOC)){
		            		to = "app";
		            	}
		    			intent2.putExtra("to", to);
		    			intent2.putExtra("phone", msgs[i].getOriginatingAddress().toString());
		    			context.sendBroadcast(intent2);
		    			flag = true;
		            }
	            }
	            
	            if(flag && flag2){
	            	Intent dialogIntent = new Intent(context, RingActivity.class);
	            	dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		        	dialogIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
		        	dialogIntent.addFlags(Intent.FLAG_FROM_BACKGROUND);
		        	String valor = "ring";
		        	if( flag3 ){
		        		valor = "silent";
		        	}
		        	dialogIntent.putExtra("tipe", valor);
	            	context.startActivity(dialogIntent);
	            }
	            if(flag){
	            	abortBroadcast();
	            }
	        }
    	}
    	config = null;
    }
}